# -*- coding: utf-8 -*-

import os
import time
from PIL import Image

from io import BytesIO

# 创建文件夹
def create_file():

    # picture_time = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
    directory_time = time.strftime("%Y-%m-%d", time.localtime(time.time()))
    # print(picture_time)
    print(directory_time)
    # 打印文件目录
    print("当前项目路径：" + os.getcwd())

    # 获取到当前文件的目录，并检查是否有 directory_time 文件夹，如果不存在则自动新建 directory_time 文件
    try:
        File_Path = os.getcwd() + "\\" + "upimage"
        print(File_Path)
        # 判断是否已经存在该目录
        if not os.path.exists(File_Path):
            # 目录不存在，进行创建操作
            os.makedirs(File_Path) #使用os.makedirs()方法创建多层目录
            print("目录新建成功：" + File_Path)
        else:
            print("目录已存在！！！")
    except BaseException as msg:
        print("新建目录失败：" + msg)

    return File_Path

# 二进制数据转化为jpg,并压缩图片
def byte_to_image(byte, image_name):

    img = Image.open(byte)
    w, h = img.size
    print(img)
    dImg = img.resize((int(w / 3), int(h / 3)), Image.ANTIALIAS)
    print('压缩成功')
    # img.show()
    # 建立一个新的空二进制管道
    imgByteArr = BytesIO()
    # 以PNG格式保存图片
    dImg.save(imgByteArr, format('PNG'))
    # 获取所有值
    imgByteArr = imgByteArr.getvalue()
    # 文件保存路径
    data_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
    data_next_path = os.path.join(data_path, 'upimage')
    with open(os.path.join(data_next_path,image_name), 'wb') as f:
        f.write(imgByteArr)

    return f